﻿using Dapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.SignalR;
using System.Data.SqlClient;
using WMSManage.Hubs;

namespace WMSManage.Filter
{
    public class OrderFilterAttribute : IAsyncActionFilter
    {
        private readonly IHubContext<ChatHub> hubContext;
        private readonly string orderType;
        private readonly string actionType;

        public OrderFilterAttribute(IHubContext<ChatHub> hubContext,string orderType,string actionType)
        {
            this.hubContext = hubContext;
            this.orderType = orderType;  //单据类型：如"销售单"、"进货单"等
            this.actionType = actionType; // 操作类型：如"待审核"、"待入库"、"待出库"等
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var result = await next.Invoke();

            bool shouldSendNotification = false;
            bool shouldAddInfoRecord = false;
            object resultValue = null;

            // 获取实际返回值
            if (result.Result is ObjectResult objectResult)
            {
                resultValue = objectResult.Value;
            }
            else if (result.Result is JsonResult jsonResult)
            {
                resultValue = jsonResult.Value;
            }

            // 检查是否为成功的整数值或者是预警类型的操作
            if (resultValue is int intValue && intValue > 0)
            {
                shouldSendNotification = true;
                shouldAddInfoRecord = true; // 普通业务操作需要添加信息记录
            }
            else if (actionType == "到期预警" || actionType == "库存预警" || actionType == "预警")
            {
                // 对于预警类型，只要方法执行成功就发送通知，但不添加信息记录
                shouldSendNotification = true;
                shouldAddInfoRecord = false; // 预警类型不添加信息记录
            }

            Console.WriteLine($"过滤器调试: Action={context.ActionDescriptor.DisplayName}, Result={resultValue}, ActionType={actionType}, 是否发送通知={shouldSendNotification}, 是否添加信息记录={shouldAddInfoRecord}");

            if (shouldSendNotification)
            {
                string title = $"{orderType}";
                string message = GetNotificationMessage(orderType, actionType);

                Console.WriteLine($"发送SignalR消息: {title} - {message}");

                await hubContext.Clients.All.SendAsync("ReceiveMessage", title, message);

                // 只有非预警类型才添加信息记录
                if (shouldAddInfoRecord)
                {
                    await AddInfoRecord(message, actionType);
                }
            }
        }

        private async Task AddInfoRecord(string message, string actionType)
        {
            try
            {
                string con = "Data Source=121.37.93.71;Initial Catalog=CSSL_ZCTWMS;User ID=sa;Password=geili@2025;Encrypt=False";
                using (SqlConnection sqlConnection = new SqlConnection(con))
                {
                    await sqlConnection.OpenAsync();
                    string sql = @"INSERT INTO [dbo].[sys_info](info_text, info_type, info_status, info_time)
                           VALUES(@info_text, @info_type, @info_status, @info_time)";

                    int result = await sqlConnection.ExecuteAsync(sql, new
                    {
                        info_text = message,
                        info_type = actionType,
                        info_status = 2,
                        info_time = DateTime.Now
                    });

                    Console.WriteLine($"信息记录添加成功，影响行数: {result}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"添加信息记录失败: {ex.Message}");
            }
        }

        private string GetNotificationMessage(string orderType, string actionType)
        {
            return actionType switch
            {
                "审核" => $"有新的{orderType}需要审核",
                "入库" => $"{orderType}审核通过，等待入库操作",
                "出库" => $"{orderType}审核通过，等待出库操作",
                "到期提醒" => $"有新的{orderType}信息，注意查看",
                "库存预警" => $"有新的{orderType}信息，注意查看",
                _ => $"有新的{orderType}信息更新"
            };
        }
    }
}
